import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'



Vue.use(VueRouter)



const router = new VueRouter({
  routes: [
    {
      path: '/', redirect: '/login'
    },
    {
      path: '/login', component: Login
    },
    {
      //Welcome是Home中实现,所以注册为其子组件,并通过重定向,只要访问home就定向到home页面
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        {
          path: '/welcome', component: Welcome,
        },
        {
          path: '/users', component: Users
        },

      ]
    },
  ]
})
//挂载导航守卫,根据访问路径,去判断是否放行,如果是需要登陆的页面,就需要验证token
router.beforeEach((to, from, next) => {
  //to 将要访问路径
  //from 从那个路径来的
  //next 函数  表示放行
  //1 直接放行 next()  2 强制跳转到路径next('/xxx')
  if (to.path === '/login') {
    return next();
  }
  //获得 token
  //const 接收一下
  const tokenStr = window.sessionStorage.getItem('token')
  console.log(tokenStr);
  if (!tokenStr) {
    return next('/login');
  }
  next();
})





export default router
